
package cc.market.controller.user;

import cc.market.VO.UserLoginVO;
import cc.market.constant.JwtClaimsConstant;
import cc.market.properties.JwtProperties;
import cc.market.service.UserService;
import cc.market.entity.User;
import cc.market.constant.MessageConstant;
import cc.market.result.Result;
import cc.market.DTO.UserDTO;
import cc.market.utils.JwtUtils;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.*;
import java.util.HashMap;
import java.util.Map;


@RestController
@RequestMapping("/user")
@Slf4j
@Tag(name = "用户相关接口")
public class UserController {

    @Autowired
    private UserService userService;

    private final BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();

    @Autowired
    private JwtProperties jwtProperties;


    @PostMapping("/register")
    @Operation(summary = "用户注册")
    public Result<String> register(@RequestBody UserDTO userDTO) {
        log.info("新增用户：{}",userDTO);
        Boolean res = userService.register(userDTO);
        if (res){
            return Result.success(MessageConstant.REGISTER_SUCCESS);
        }
        else {
            return Result.error(MessageConstant.ACCOUNT_ALREADY);
        }
    }

    @GetMapping("/login")
    @Operation(summary = "用户登陆")
    public Result login(@RequestParam String phone,
                        @RequestParam String password){
        User user = userService.getByPhone(phone);
        if (user == null) {
            // 账号不存在
            return Result.error(MessageConstant.ACCOUNT_NOT_FOUND);
        }

        // 检查账号是否被锁定
        if (user.getStatus() == 1) {
            return Result.error(MessageConstant.ACCOUNT_LOCKED);
        }

        // 对密码进行bcrypt加密，然后检查加密过的密码是否匹配
        if (!passwordEncoder.matches(password, user.getPassword())) {
            return Result.error(MessageConstant.PASSWORD_ERROR);
        }

        // 登录成功
        //登录成功后，生成jwt令牌
        Map<String, Object> claims = new HashMap<>();
        claims.put(JwtClaimsConstant.USER_ID, user.getId());
        String token = JwtUtils.generateJWT(jwtProperties.getUserSecretKey(), jwtProperties.getUserTtl(), claims);

        UserLoginVO userLoginVO =UserLoginVO.builder()
                                            .token(token)
                                            .build();
        BeanUtils.copyProperties(user, userLoginVO);
        return Result.success(MessageConstant.LOGIN_SUCCESS,userLoginVO);

    }

    @PostMapping("/update")
    @Operation(summary = "更新用户信息")
    public Result<String> updateUserInfo(@RequestBody User user){
        userService.update(user);
        return Result.success(MessageConstant.UPDATE_SUCCESS);
    }

    @GetMapping("/get")
    @Operation(summary = "根据用户ID获取信息")
    public Result<User> getById(@RequestParam Integer id){
        log.info("根据{}查询用户",id);
        User user = userService.getById(id);
        if (user == null){
            return Result.error(MessageConstant.ACCOUNT_NOT_FOUND);
        }
        return Result.success(MessageConstant.SEARCH_SUCCESS,user);
    }
    @PostMapping("/updatePwd")
    @Operation(summary = "更新用户密码")
    public Result<String> updatePwd(@RequestBody Map<String, Object> data){
        Integer id = (Integer) data.get("id");
        String pwd = (String) data.get("pwd");
        userService.updatePwd(id,pwd);
        return Result.success(MessageConstant.UPDATE_SUCCESS);
    }
}